<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fun"%>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="zh-cn">
<head>
    <title>智能锁注册</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
    <meta name="renderer" content="webkit">
    <meta content="yes" name="apple-mobile-web-app-capable">
    <meta content="black" name="apple-mobile-web-app-status-bar-style">
    <meta content="telephone=no" name="format-detection">
    <meta content="email=no" name="format-detection">
    <meta name="viewport"
	content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
	<link href="${pageContext.request.contextPath}/static/css/KeysManager/AddLock.css?date=1" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/static/plugins/layer_mobile/need/layer.css" rel="stylesheet">
    <link href="${pageContext.request.contextPath}/static/css/app-theme/${appid}.css" rel="stylesheet">
    <script rel="script" src="${pageContext.request.contextPath}/static/js/KeysManager/index.js?sate=2"></script>
    <script src="${pageContext.request.contextPath}/static/js/jquery-1.11.3.min.js"></script>
    <script src="${pageContext.request.contextPath}/static/plugins/layer_mobile/layer.js" type="text/javascript"></script>
    <%-- <script src="${pageContext.request.contextPath}/static/js/jquery.form.js" type="text/javascript"></script> --%>
    <script src="${pageContext.request.contextPath}/static/js/yahlj-app.js?v=s1"></script>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/js/mobileSelect.css">
    <script src="${pageContext.request.contextPath}/static/js/mobileSelect.js" type="text/javascript"></script>
    <script src="${pageContext.request.contextPath}/static/js/json_adress.min.js?v=2" type="text/javascript"></script>
    
    
    
    
    <style type="text/css">
        input{
            box-sizing: content-box;
        }
        .dw-persp{
        	bottom:0!importamt;
        }
        .dw{
        	    position: fixed!importamt;
        	    bottom:0!importamt;
        }
        .mobileSelect .content .btnBar .ensure{
				color:e4bf8b;
		}
      </style>
</head>
<body>
<div class="title clearfix">
<div class="lf" style="font-size:14px;">
		<div>请打开蓝牙设备，自动获取信息</div>
		<div>也可扫一扫获取信息</div>
	</div>
	<div class="rt Scan_btn" onclick="scanclick()">
		扫一扫
	</div>
    	<%-- <img class="scan" onclick="scanclick()" src="${pageContext.request.contextPath}/static/images/KeysManager/scan.png"/>
    	<p class="scan-info">扫码自动输入PID输入、激活码</p> --%>
</div>
<form id="uploadForm">
            <input type="hidden" name="type" id="type" value="${type}" />
            <input type="hidden" name="typeAPP" id="typeAPP" value="0">
    <div class="content">

       <div class="item">
        	<div class="item_title">PID</div>
          <%--   <img class="icon" src="${pageContext.request.contextPath}/static/images/KeysManager/PID.png"/> --%>
            <input type="text" name="pid" id="pid" class="edittext" placeholder="请输入PID"  value="${pid}" />
            <div class="gain_PID" id='gain_PID' onclick="pid_change()">重新获取</div>
        </div>
        <div class="item">
        	<div class="item_title">激活码</div>
            <%-- <img class="icon" src="${pageContext.request.contextPath}/static/images/KeysManager/activationCode.png"/> --%>
            <input type="text" name="checkCode" id="checkCode" class="edittext" placeholder="请输入激活码"  value="${checkcode}" />
        </div>

        <div class="item">
        	<div class="item_title">您的姓名</div>

           <%--  <img class="icon" src="${pageContext.request.contextPath}/static/images/KeysManager/editName.png"/> --%>

            <input type="text" name="communityName" id="communityName" class="edittext" placeholder="请输入您的姓名"/>

        </div>

        <div class="item">
        	<div class="item_title">锁的名称</div>

           <%--  <img class="icon" src="${pageContext.request.contextPath}/static/images/KeysManager/key.png"/> --%>

            <input type="text" name="lockName" id="lockName" class="edittext" placeholder="请输入智能锁名称(如：我的家门)"/>

        </div>

        <div class="item">
        	<div class="item_title">所在城市</div>

            <%-- <img class="icon" src="${pageContext.request.contextPath}/static/images/KeysManager/address.png"/> --%>

            <!--<input type="text" name="address" id="address" class="" placeholder="请选择"/>-->

            <div class="content-block">
                <!-- <input id="demo2" type="text" readonly="" class="edittext" placeholder="请选择您所在的城市（选填）" areaid="" />
                <input id="value2" type="hidden" /> -->
                
                
                 <input id="demo2" placeholder="请选择您所在的城市（选填）" readonly="readonly" class="edittext" onfocus="this.blur()" areaid="" style="cursor: pointer;">
                
            </div>

        </div>
        <div class="item">
        	<div class="item_title">详细地址</div>
            <input type="text" name="street" id="street" class="edittext" placeholder="请输入详细地址（选填）"/>
        </div>
        <c:if test="${loginedFlag=='0'}">
	         <div class="item">
	        	<div class="item_title">手机号码</div>
	            <input type="text" class="edittext" name="tel" id="tel" value="${tel}" placeholder="请输入您的手机号"/>
	            <div class="gain_PID1 " id="send" data-able='1'>获取验证码</div>
	        </div>
	        
	         <div class="item">
	        	<div class="item_title">验证码</div>
	            <input type="text" name="yzm" id="yzm" class="inputVerify" placeholder="请输入验证码"  value="" />
	        </div>
	        
	        <div class="item" id='pwd1'>
	        	<div class="item_title">密码</div>
	            <input type="password" name="pwd_entry" id="pwd_entry" class="pwd_entry edittext" placeholder="请设置6-16位登陆密码"  value="" />
	        </div>
	        
	        <div class="item" id='pwd2'>
	        	<div class="item_title">密码</div>
	            <input type="password" name="again_pwd" id="again_pwd" class="again_pwd edittext" placeholder="请确认登密码"  value="" />
	        </div>
        </c:if>
        
<!--         <div class="item">
        	<a onclick="test()">测试</a>
        </div> -->
    </div>
    
   
    
   
   <%--  <div class="verifty">
            <img class="icon" src="${pageContext.request.contextPath}/static/images/KeysManager/verification.png"/>
            <input type="text" class="inputVerify" name="yzm" id="yzm" placeholder="请输入验证码"/>
    </div> --%>
</form>
    <!-- <button class="get-verify" id="send">发送验证码</button> -->

    <div class="foot">
         <button type="submit" name="enter"  id="submit" onclick="doUpload()">确定</button>
    </div>
    
<script type="text/javascript">
    var province=AddressInfo['Provinces'];
    var Cities=AddressInfo['Cities'];
    var Districts=AddressInfo['Districts'];
    var all_json_arr=[];
    for(var x=0;x<province.length;x++){
        var _provicename=province[x]._provicename;
        var _provincecode=province[x]._provincecode;
        var _proviceid=province[x]._proviceid;
        var city_arr=[];
        for(var h=0;h<Cities[_proviceid].length;h++){
            var _cityname=Cities[_proviceid][h]._cityname;
            var _citycode=Cities[_proviceid][h]._citycode;
            var _cityid=Cities[_proviceid][h]._cityid;
            var districts_arr=[];
            for(var y=0;y<Districts[_cityid].length;y++){
                var _districtname=Districts[_cityid][y]._districtname;
                var _districtcode=Districts[_cityid][y]._districtcode;
                var _cityid=Districts[_cityid][y]._cityid;
                var districts_json={id:_districtcode,value:_districtname};
                districts_arr.push(districts_json)
            }
            var city_json=
                    {id:_citycode,value:_cityname,
                    childs:districts_arr
                    };
            city_arr.push(city_json)
        }
        var all_json=
        {
            id:_provincecode,
            value:_provicename,
            childs:city_arr,
        };
        all_json_arr.push(all_json);
    }
    var mobileSelect = new MobileSelect({
    trigger: '#demo2',
    title: '',
    wheels: [
        {data:all_json_arr}
    ],
    transitionEnd:function(indexArr, data){
        var len=data.length;
        var value=[];
        var id=[];
        for(var z=0;z<len;z++){
            value.push(data[z].value);
/*             id.push(data[2].id);*/    
        }
        $("#demo2").val(value);
        $("#demo2").attr("areaid",data[2].id);

    },
    callback:function(indexArr, data){
        var len=data.length;
        var value=[];
        var id=[];
        for(var z=0;z<len;z++){
            value.push(data[z].value);
            /*             id.push(data[2].id);*/    
        }
        $("#demo2").val(value);
        $("#demo2").attr("areaid",data[2].id);
    }
});


</script>
<script>

(function bottonm(){  
    if($(document).height()<$(window).height()){  
        $('.dw').css({'position':'fixed','bottom':'0px'});  
        $(document).height($(window).height()+'px');  
    }  
})();  



function test(){
	hljJs.userLogin('932378934695539644','20170714164529118-31d44481bf7b44d29b439fd8d980280a','18758027521',{
			success:function(res){
				
			},
			fail:function(res){
				alert(res)
			}
		});       
}

var appid='';
var loginedFlag='${loginedFlag}';//app的登录状态
var loginedFlag_='${loginedFlag}';

window.onload=function(){
	setTimeout("dosm()",500);	
}
function dosm(){
	//pid_change();
	
	hljJs.getAppid({
		success:function(res){
			appid = res;
		},
		fail:function(res){
			layerAlert("获取APP信息失败");
		}
	});	
}

	/* var area2 = new LArea();
	area2.init({
		'trigger': '#demo2',
		'valueTo': '#value2',
		'keys': {
			id: 'value',
			name: 'text'
		},
		'type': 2,
		'data': [provs_data, citys_data, dists_data]
	}); */
	var valo = $("#demo2").attr("areaid");
	$('#demo2').scroller('destroy').scroller({ preset: 'area', theme: 'android-ics light', display: 'bottom',valueo:valo });
	
	
function locationReplace(url){
	  if(history.replaceState){
	    history.replaceState(null, document.title, url);
	    history.go(0);
	  }else{
	    location.replace(url);
	  }
}
	
	
	var badArr = {};
	var goodArr = {};
	
	function scanclick(){
		hljJs.scanCode({
			success:function(res){
				
				
			},
			fail:function(res){
					layerAlert('获取失败');						
			}
		});
	}
	
	function callbackScanCode(result){
	  	if(result.code==1){
			var resultStr = result.resultStr;
			if(resultStr.indexOf("tlocks_a.action")>-1){
				window.location.href=resultStr;
				return;
			}
			if(resultStr.indexOf(",")>0){
				var arr = resultStr.split(",");
				$("#pid").val(arr[0]);
				$("#checkCode").val(arr[1]);
			}else{
				if(resultStr.indexOf("?p=")<0){
					layer.open({
			    	    content: "无法获取PID，请重试",
			    	    btn: '我知道了'
			    	  });
			    	  return;
				}
				if(resultStr.indexOf("&c=")<0){
					layer.open({
			    	    content: "无法获取激活码，请重试",
			    	    btn: '我知道了'
			    	  });
					 return;
				}
				var arr1 = resultStr.split("?p=");
				var arr2 = arr1[1].split("&c=");
				var arr3 = arr2[1].split("&v=");	
				$("#pid").val(arr2[0]);
				$("#checkCode").val(arr3[0]);
				
			}
		}else if(result.code==2){
		}else{
			layer.open({
	    	    content: "获取二维码扫描结果失败，请重试",
	    	    btn: '我知道了'
	    	  });
		} 
	}
	function doUpload(){
		$("#submit").attr("disabled", "true");
		var pid = $("#pid").val();
		var checkCode = $("#checkCode").val();
	    var communityName = $("#communityName").val();
	    var lockName = $("#lockName").val();
	    var type = $("#type").val();
        var areaCode = $("#demo2").attr("areaid");
/*         if(!areaCode){
	    	layerAlert("所属区域必填");
	    	 $("#submit").removeAttr("disabled");
	    	 return;
	    } */
        var areaCodeArr = areaCode.split(" ");
	    areaCode = areaCodeArr[areaCodeArr.length-1];
	    var street = $("#street").val();
	    if(!pid){
	    	 layerAlert("PID必填");
	    	 $("#submit").removeAttr("disabled");
	    	 return;
	    }
	    if(!checkCode){
	    	 $("#submit").removeAttr("disabled");
	    	layerAlert("激活码必填");
	    	 return;
	    }
	    if(!communityName){
	    	 layerAlert("姓名必填");
	    	 $("#submit").removeAttr("disabled");
	    	 return;
	    }
	    if(!lockName || lockName.length>10){
	    	layerAlert("智能锁名称在10字以内");
	    	 $("#submit").removeAttr("disabled");
	    	 return;
	    }
/* 	     if(!areaCode){
	    	layerAlert("所属区域必填");
	    	 $("#submit").removeAttr("disabled");
	    	 return;
	    }  */
	    var areaCodeArr = areaCode.split(",");
	    areaCode = areaCodeArr[areaCodeArr.length-1];
	    var departTel = $("#tel").val();
	    var yzm = $("#yzm").val();
	    var pwd_entry = $("#pwd_entry").val();
	    var again_pwd = $("#again_pwd").val();
	    if(loginedFlag=='0'||loginedFlag=='2'){
		    if(!departTel){
		    	layerAlert("手机号必填");
		    	 $("#submit").removeAttr("disabled");
		    	 return;
		    }else if(!(/^1[3|4|5|7|8]\d{9}$/.test(departTel))){ 
		    	layerAlert("用户手机号有误，请填写有效手机号"); 
		        $("#submit").removeAttr("disabled");
		        return; 
		    }
		    if(!yzm){
		    	layerAlert("验证码必填");
		    	$("#submit").removeAttr("disabled");
		    	return;
		    }else if(!(/^\d{6}$/.test(yzm))){
		    	layerAlert("验证码有误，请填写6位有效数字"); 
		    	$("#submit").removeAttr("disabled");
			    return; 
			}
		    if(loginedFlag=='0'){
	    	  if(!pwd_entry||!again_pwd){
			      layerAlert("密码必填");
			      $("#submit").removeAttr("disabled");
			       return;
			   }
	    	   if(pwd_entry!=again_pwd){
	    		   layerAlert("密码不一致");
				   $("#submit").removeAttr("disabled");
				   return;
	    	   }
		    }
		    if(!appid){
		    	layerAlert("获取app信息失败");
		    	 $("#submit").removeAttr("disabled");
		    	 return;
		    }
			
	    }else{
	    	
	    	
	    }
	    
	    $.post("${pageContext.request.contextPath}/register/tComuLockAdd.action", {
	    	'typeAPP': '0',
		    'pid': pid,
		    'checkCode': checkCode,
		    'communityName': communityName,
		    'lockName': lockName,
	        'areaCode': areaCode,
		    'street': street,
	    	'departTel': departTel,
	    	'yzm': yzm,
	    	'type': type,
	    	'departTel': departTel,
	    	'pwd': pwd_entry,
	    	'again_pwd': again_pwd,
	    	'appid':appid,
	    	'loginedFlag':loginedFlag
	    	
         }, function (result) {
             result = JSON.parse(result)
             if (result.code == 1) {
            	 if(loginedFlag=='0'||loginedFlag=='2'){
            		 hljJs.userLogin(result.userid,result.token,departTel,{
              			success:function(res){
              				locationReplace("${pageContext.request.contextPath}/admin/loginByApp.action");
              			},
              			fail:function(res){
              				layerAlert('请登录app');
              			}
              		});            		 
            	 }else{
            		 locationReplace("${pageContext.request.contextPath}/admin/loginByApp.action");	 
            	 }
             }else{
            	 $("#submit").removeAttr("disabled");
            	 layerAlert(result.msg);
             }
         });
	}
	function layerAlert(msg){
		layer.open({
    		title:"<div style='margin-top:9px;font-weight: bold;'>温馨提示</div>",
    	    content: "<div style='margin-top:10px;'>"+msg+"</div>",
    	    btn: '我知道了'
    	});
		
		/* layer.open({
      	    content: msg,
      	    btn: '我知道了'
      	}); */
	}
	
	/*PID正在获取和重新获取的状态 */
    function pid_change(){
    	$("#gain_PID").text("正在获取");
    	var okPid='';
    	hljJs.scanBlue({
    		success:function(res){
				if(res.code=='1'){
					if(res.blue_state=='0'){
						layerAlert('请开启蓝牙');
					}else{
						var macs='';
						var names ='';
						for(var i in res.data){
							var d = res.data[i];
							var name = d.name;
							var rssi = d.rssi;
							var manufacturerData = d.manufacturerData;
							var mac = '';
							if(name.length>0){
								if(name.indexOf('MD_')>-1){//我们设备名以MD_开头
									manufacturerData = manufacturerData.replace(" ","");
									if(manufacturerData.length>=16){
										mac = manufacturerData.substr(4,12);
									}else if(typeof(d.mac)!="undefined"&&d.mac.length>0){ 
										mac = d.mac;
									}else{
										continue;
									}
									macs+=mac+",";
									names+=name+",";
								}
							}
						}		
						if(macs.length>0){
							$.ajax({   
							    url:'${pageContext.request.contextPath}/admin/tlocks_getActiveInfo.action',   
							    type:'post',   
							    data:'mac='+macs+'&device_name='+names+'&appid='+appid,   
							    async : true, //默认为true 异步   
							    dataType:'json',
							    error: function(XMLHttpRequest, textStatus, errorThrown) {
							    	layerAlert('请求失败！');
							    },  
							    success:function(data){   
							    	var okFlag =  false;
							    	if (data.code == 1) {
							    		for(var o in data.data){
							    			var d = data.data[o]
							    			 if(d.bizerr=='1'){
												var pid = d.pid;
												var checkcode=d.checkcode;
												$("#pid").val(pid);
												$("#checkCode").val(checkcode);
												$("#gain_PID").text("重新获取");
												layerAlert_PID();
												okFlag=true;
							            	 }
							    		}
						             }else{

						             }
							    	
							    	if(!okFlag){
							    		layerAlert('未找到设备');
							    	}
							    }
							});
							
						}else{
							layerAlert('未找到设备，请靠近设备或确认设备状态正确');
						}
						
					}
				}else{
					layerAlert('获取失败');
				}
				$("#gain_PID").text("重新获取");
			},
			fail:function(res){
				if("-1000"==res){
					layerAlert('此版本app不支持蓝牙获取设备信息');
				}else{
					layerAlert('获取失败.');						
				}
				$("#gain_PID").text("重新获取");
			}
		});
    } 
	/*核对PID提示框 */
	function layerAlert_PID(){
		layer.open({
			title: '温馨提示',
      	    content: "请与设备上的PID进行核对，如不符合将会影响您的设备操作",
      	    btn: '确定'
      	});
	}
</script>

<script type="text/javascript">
var time = 60;
var btnSend;
var timer;
$(document).ready(function () {
    btnSend = $("#send");
    btnSend.click(function () {
    	var phonenum = $("#tel").val();
	    if(!isPhoneNum(phonenum)){
	    	layer.open({
	    		title:"<div style='margin-top:9px;font-weight: bold;'>温馨提示</div>",
        	    content: "<div style='margin-top:10px;'>用户手机号填写不正确，请重新输入</div>",
        	    btn: '我知道了'
        	});
	    	return;
		}
	    if(btnSend.attr("data-able")=='1'){
	    	$.post("/admin/sendCode4BindApp.action", {
		     	'phone': phonenum,
		     	'appid':appid
		      }, function (result) {
		          result = JSON.parse(result)
		          if (result.code == 1) {
		        	  layer.open({
		        		  title:'友情提示',
		          	      content: '已发送',
		          	      btn: '我知道了'
		          	});
		        	  btnSend.html("剩余 " + time + " 秒");
		              //btnSend.attr("disabled", "disabled");
		              btnSend.attr("data-able", "0");
		              setTimeout(function () {
		                  checkTime();
		              }, 1000);
		              
		              if(result.isUserExit=='1'){//用户已存在
		            	  $("#pwd1").hide();
		            	  $("#pwd2").hide();
		            	  loginedFlag='2';
		              }else{
		            	  loginedFlag=loginedFlag_;
		            	  $("#pwd1").show();
		            	  $("#pwd2").show();
		              }
		              
		          }else{
		        	  layer.open({
		        		    title:'友情提示',
			          	    content: result.msg,
			          	    btn: '我知道了'
			          	});
		        	  time = 60;
		              //btnSend.removeAttr("disabled");
		              btnSend.attr("data-able", "1");
		              btnSend.html("获取验证码");
		              window.clearInterval(timer);
		          }
		      });
	    }
    });
});

//校验手机号是否合法
function isPhoneNum(phonenum){
    var myreg = /^1[3|4|5|7|8]\d{9}$/; 
    if(!myreg.test(phonenum)){ 
        return false; 
    }else{
        return true;
    }
}
function checkTime() {
    if (time == 0) {
        time = 60;
        btnSend.removeAttr("disabled");
        btnSend.attr("data-able", "1");
        btnSend.html("获取验证码");
        window.clearInterval(timer);
    } else {
        time--;
        btnSend.html("剩余 " + time + " 秒");
        setTimeout(function () {
            checkTime()
        }, 1000);
    }
}

</script>
</body>
</html>
